package com.huatai.exchange.impl;

import com.faneui.common.exception.BusinessException;
import com.faneui.common.utils.*;
import com.huatai.exchange.dal.dao.*;
import com.huatai.exchange.dal.model.*;
import com.huatai.exchange.deal.FileCreateDealFactory;
import com.huatai.exchange.facade.*;
import com.huatai.exchange.integration.base.service.FileOperateService;
import com.huatai.exchange.service.ExcDataFileInfoService;
import com.huatai.exchange.utils.FileDealUtils;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.*;

@Service
public class ExcDataFileInfoServiceImpl implements ExcDataFileInfoService {

    private static final Logger logger = LoggerFactory.getLogger(ExcDataFileInfoService.class);

    @Autowired
    private ExcExchangeDateFileDAO excExchangeDateFileDAO;

    @Autowired
    private ExcExchangeInfoDAO excExchangeInfoDAO;

    @Autowired
    protected FileOperateService fileOperateService;

    @Autowired
    private ExcDataFileInfoDAO dateFileInfoDAO;

    @Autowired
    private FileCreateDealFactory dealFactory;

    @Override
    public void getFileList(String exchangeId, Map<String, Object> resvMap) throws BusinessException {
        ExcExchangeInfo excExchangeInfo = excExchangeInfoDAO.queryById(exchangeId);
        List<ExcExchangeDateFile> dataFileList = excExchangeDateFileDAO.queryByExchangeInfoId(excExchangeInfo.getId());
        if (ListUtils.isEmpty(dataFileList))
            return;
        StringBuffer fileNames = new StringBuffer("");
        StringBuffer filePaths = new StringBuffer("");
        //  遍历数据文件信息，获取文件
        for (ExcExchangeDateFile dateFile : dataFileList) {
            ExcDataFileInfo dataFileInfo = dateFileInfoDAO.queryById(dateFile.getDateFileId());
            dealFactory.getDealService(dataFileInfo.getType()).downloadCreateFile(fileNames, filePaths, dateFile, dataFileInfo, resvMap);
        }
        logger.info("完成文件准备：" + DateFormatUtils.HHmmss.format(new Date()));
        // 压缩设置
        if (StringUtils.isBlank(filePaths.toString())) {
            return;
        }
        if (Contents.boolean_true.equals(excExchangeInfo.getIsZip())) {

            filePaths = new StringBuffer(fileOperateService.uploadZipFiles(filePaths.toString().substring(1)
                    , fileNames.toString().substring(1), Contents.boolean_false));
            logger.info("重新压缩文件：" + DateFormatUtils.HHmmss.format(new Date()));
            fileNames = new StringBuffer(FileDealUtils.formatStr(excExchangeInfo.getZipName(), null, resvMap));
            resvMap.put("fileNames", fileNames.toString());
            resvMap.put("filePaths", filePaths.toString());
        } else {
            resvMap.put("fileNames", fileNames.toString().substring(1));
            resvMap.put("filePaths", filePaths.toString().substring(1));
        }
    }


}
